package com.piece.module.spider.support;

import com.piece.module.spider.annotation.Comment;
import com.piece.module.spider.annotation.Example;
import com.piece.module.spider.annotation.Return;
import lombok.Data;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Data
public class Grammer {

	private String owner;

	private String method;

	private String comment;

	private String example;

	private String function;

	private List<String> returns;

	public static List<Grammer> findGrammers(Class<?> clazz, String function, String owner, boolean mustStatic) {
		Method[] methods = clazz.getDeclaredMethods();
		List<Grammer> grammers = new ArrayList<>();
		for (Method method : methods) {
			if (Modifier.isPublic(method.getModifiers()) && (Modifier.isStatic(method.getModifiers()) || !mustStatic)) {
				Grammer grammer = new Grammer();
				grammer.setMethod(method.getName());
				Comment comment = method.getAnnotation(Comment.class);
				if(null != comment){
					grammer.setComment(comment.value());
				}
				Example example = method.getAnnotation(Example.class);
				if (null != example){
					grammer.setExample(example.value());
				}
				Return returns = method.getAnnotation(Return.class);
				if (null != returns) {
					Class<?>[] types = returns.value();
					List<String> returnTypes = new ArrayList<>();
					for (int i = 0; i < types.length; i++) {
						returnTypes.add(types[i].getSimpleName());
					}
					grammer.setReturns(returnTypes);
				} else {
					grammer.setReturns(Collections.singletonList(method.getReturnType().getSimpleName()));
				}
				grammer.setFunction(function);
				grammer.setOwner(owner);
				grammers.add(grammer);
			}
		}
		return grammers;
	}
}
